<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        canvas {
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
<canvas width="600" height="400"></canvas>
<script>

    var myCanvas = document.querySelector('canvas');
    var ctx = myCanvas.getContext('2d');

    var data = [
        {
            title: '15-20岁',
            num: 6
        },
        {
            title: '20-25岁',
            num: 30
        },
        {
            title: '25-30岁',
            num: 10
        },
        {
            title: '20岁以上',
            num: 8
        }
    ];

    /*1.绘制饼状图*/
    /*1.1 绘制一个饼图*/
    /*1.2 绘制标题 从扇形的弧的中心伸出一条线，画一条横线，文字填充*/
    /*1.3 在画布的左上角 绘制说明 一个和扇形一样颜色的矩形 旁边就是文字说明*/

    var PieChart = function (ctx) {
        this.ctx = ctx || document.querySelector('canvas').getContext('2d');

        this.w = this.ctx.canvas.width;
        this.h = this.ctx.canvas.height;
        /*圆的中心*/
        this.x0 = this.w / 2 + 40;
        this.y0 = this.h / 2;
        /*半径*/
        this.radius = 150;
        /*伸出去的线的长度*/
        this.outLine = 20;
        /*说明的矩形大小*/
        this.rectW = 30;
        this.rectH = 16;
        this.space = 10;
    };

    PieChart.prototype.init = function (data) {
        this.drawPie(data);
    };

    PieChart.prototype.drawPie = function (data) {
        var that = this;
        /*转化弧度*/
        var angleList = this.transformAngle(data);
        // console.log(angleList);
        var startAngle = 0;
        angleList.forEach(function (item, index) {
            /*当前的结束弧度为下一次的起始弧度*/
            var endAngle = startAngle + item.angle;
            ctx.beginPath();
            ctx.moveTo(that.x0,that.y0);
            ctx.arc(that.x0,that.y0,that.radius,startAngle,endAngle);
            var lineColor = ctx.fillStyle = that.getRandomColor();
            ctx.fill();

            /*绘制标题*/
            that.drawTitle(startAngle,item.angle,lineColor,item.title);
            /*绘制说明*/
            that.drawDesc(index,item.title);
            startAngle = endAngle;
        });
    };

    PieChart.prototype.drawTitle = function (startAngle,angle,color,title) {
        /*1.确定伸出去的线，通过圆心 伸出去的点 确定这个线*/
        /*2.确定圆外的点 需要伸出去的长度*/
        /*3.计算点的坐标 sin cos*/
        /*弧度： 当前扇形的起始弧度 + 对应的弧度的一半*/
        /*outX= x0 + cos（angle） * （r + outline）*/
        /*outY= x0 + sin（angle） * （r + outline）*/
        var edge = this.radius + this.outLine;
        var edgeX = Math.cos(startAngle + angle / 2) * edge;
        var edgeY = Math.sin(startAngle + angle / 2) * edge;
        /*计算出去的点坐标*/
        var outX = this.x0 + edgeX;
        var outY = this.y0 + edgeY;

        this.ctx.beginPath();
        this.ctx.moveTo(this.x0, this.y0);
        this.ctx.lineTo(outX,outY);
        ctx.strokeStyle = color;
        /*画文字和下划线*/
        /*线的方向根据原点 通过两点的x轴来判断*/
        this.ctx.textBaseline = 'bottom';
        this.ctx.font = '14px Microsoft YaHei';
        var textWidth = this.ctx.measureText(title).width;
        if(outX > this.x0) {
            // 右侧
            this.ctx.lineTo(outX + textWidth, outY);
            this.ctx.textAlign = 'left';
        } else {
            // 左侧
            this.ctx.lineTo(outX - textWidth, outY);
            this.ctx.textAlign = 'right';
        }
        this.ctx.stroke();
        this.ctx.fillText(title,outX,outY);
    };

    PieChart.prototype.drawDesc = function (index,title) {
        /*矩形的大小，距离上和左边的间距，矩形之间的间距*/
        this.ctx.fillRect(this.space,this.space + index * (this.rectH + this.space),this.rectW,this.rectH);
        /*绘制文字*/
        this.ctx.beginPath();
        this.ctx.textAlign = 'left';
        this.ctx.textBaseline = 'top';
        this.ctx.font = '12px Microsoft YaHei';
        this.ctx.fillText(title,this.space+this.rectW+10,this.space + index * (this.rectH + this.space))
    };

    PieChart.prototype.transformAngle = function (data) {
        /*返回的数据是包含弧度的*/
        var total = 0;
        data.forEach(function (item, index) {
            total += item.num
        });
        /*计算弧度，追加到当前的对象内容*/
        data.forEach(function (item, index) {
            var angle = item.num / total * Math.PI * 2;
            item.angle = angle;
        });
        return data;
    };

    PieChart.prototype.getRandomColor = function () {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return 'rgb('+r+','+g+','+b+')'
    };

    var pieChart = new PieChart();
    pieChart.init(data);

</script>
</body>
</html>
